<?php

namespace backend\controllers;


use common\components\CurlHelper;
use common\components\Helper;
use common\components\Upload;

class FileController extends AdminController
{
    public $enableCsrfValidation = false;


    public function acionFetch()
    {
        $type = $_COOKIE['__fileupload_type'];;
        $type = in_array($type, array('image','audio')) ? $type : 'image';

        $url = trim(\Yii::$app->request->get('url'));
        $resp = CurlHelper::ihttp_get($url);
        if (Helper::is_error($resp)) {
            $result['message'] = '提取文件失败, 错误信息: '.$resp['message'];
            die(json_encode($result));
        }
        if (intval($resp['code']) != 200) {
            $result['message'] = '提取文件失败: 未找到该资源文件.';
            die(json_encode($result));
        }
        $ext = '';
        if ($type == 'image') {
            switch ($resp['headers']['Content-Type']){
                case 'application/x-jpg':
                case 'image/jpeg':
                    $ext = 'jpg';
                    break;
                case 'image/png':
                    $ext = 'png';
                    break;
                case 'image/gif':
                    $ext = 'gif';
                    break;
                default:
                    $result['message'] = '提取资源失败, 资源文件类型错误.';
                    die(json_encode($result));
                    break;
            }
        } else {
            $result['message'] = '提取资源失败, 仅支持图片提取.';
            die(json_encode($result));
        }

    }


    public function actionUpload()
    {
        if (empty($_FILES['file']['name'])) {
            $message['message'] = '上传失败, 请选择要上传的文件！';
            die(json_encode($message));
        }
        if ($_FILES['file']['error'] != 0) {
            $message['message'] = '上传失败, 请重试.';
            die(json_encode($message));
        }
        $result = Upload::uploadByName('file','images',false);
        if ($result === false) {
            $message['message'] = '上传失败';
            die(json_encode($message));
        }

        $originname = $_FILES['file']['name'];
        $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
        $ext = strtolower($ext);

        $info = array(
            'name' => $originname,
            'ext' => $ext,
            'filename' => $result,
            'attachment' => $result,
            'url' => Upload::checkGetUrl($result),
            'is_image' => 1,
            'filesize' => filesize(Upload::checkGetPath($result)),
        );

        die(json_encode($info));
    }


}

?>